import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';

import 'page_config.dart';

class WebPage extends StatefulWidget {
  final PageData pageData;

  WebPage({required this.pageData});

  @override
  State<StatefulWidget> createState() {
    return _WebPageState();
  }
}

class _WebPageState extends State<WebPage> {
  late InAppWebViewController _controller;

  @override
  Widget build(BuildContext context) {
    final keywordList = widget.pageData.parserKeyword();
    print("keywordList:$keywordList");
    final options = InAppWebViewGroupOptions();
    options.android.builtInZoomControls = false;
    options.android.loadWithOverviewMode = false;
    options.android.textZoom = 100;
    options.android.displayZoomControls = false;
    options.android.useWideViewPort = false;
    options.crossPlatform.useShouldOverrideUrlLoading = true;
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarIconBrightness: widget.pageData.cc == 1
          ? Brightness.dark
          : Brightness.light,
      statusBarColor: widget.pageData.toColor(),
    ));
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        color: Colors.white,
        home: WillPopScope(
        onWillPop: () async {
          final canBack = await _controller.canGoBack();
          if (canBack != null && canBack == true) {
            await _controller.goBack();
            return false;
          }
          return true;
        },
        child: SafeArea(child: Container(
          width: double.infinity,
          height: double.infinity,
          color: Colors.white,
          child: InAppWebView(
            initialOptions: options,
            onPageCommitVisible: (controller, uri) {
              _controller = controller;
            },
            initialUrlRequest:
            URLRequest(url: WebUri(widget.pageData.aa)),
            shouldOverrideUrlLoading:
                (controller, navigationAction) async {
              final url = navigationAction.request.url;
              if (url == null || url.toString().isEmpty) {
                return NavigationActionPolicy.CANCEL;
              }
              final urlStr = url.toString();
              print("urlStr:$urlStr");
              for (var element in keywordList) {
                if (urlStr.contains(element)) {
                  launchUrl(url, mode: LaunchMode.externalApplication)
                      .then((value) => {});
                  return NavigationActionPolicy.CANCEL;
                }
              }
              return NavigationActionPolicy.ALLOW;
            },
          ),
        ))));
  }
}
